package com.innjia.base.zima.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.antgroup.zmxy.openplatform.api.DefaultZhimaClient;
import com.antgroup.zmxy.openplatform.api.ZhimaApiException;
import com.antgroup.zmxy.openplatform.api.internal.util.EncryptionModeEnum;
import com.antgroup.zmxy.openplatform.api.internal.util.SignTypeEnum;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCustomerCertificationCertifyRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCustomerCertificationInitializeRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCustomerCertificationQueryRequest;
import com.antgroup.zmxy.openplatform.api.request.ZhimaCustomerContractInitializeRequest;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCustomerCertificationInitializeResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCustomerCertificationQueryResponse;
import com.antgroup.zmxy.openplatform.api.response.ZhimaCustomerContractInitializeResponse;
import com.innjia.base.common.ZimaConfig.SignBizCodeEnum;

/**
 * 芝麻可信电子合约签约
 * @author fangcheng.huang
 *
 */
public class ZhimaContractUtil{

	private static String PRODUCT_CODE = "w1010100000000002978";
	
	/**
	 * 可信签约初始化
	 * @param params
	 * @return
	 * ZhimaCustomerContractInitializeResponse
	 * @throws ZhimaApiException 
	 */
	public static ZhimaCustomerContractInitializeResponse contractInit(Map<String, String> params) throws ZhimaApiException {
		ZhimaCustomerContractInitializeRequest req = new ZhimaCustomerContractInitializeRequest();
		req.setProductCode(PRODUCT_CODE);
		req.setContractName(params.get("contractName"));
		req.setContractFile(params.get("contractFile"));// 必要参数
		DefaultZhimaClient client = new DefaultZhimaClient(params.get("gatewayUrl"), params.get("appId"), 
				params.get("privateKey"), params.get("zimaPublicKey"));
		return client.execute(req);
	}
	
	/**
	 * 芝麻认证初始化
	 * @param params
	 * @return
	 * ZhimaCustomerCertificationInitializeResponse
	 * @throws ZhimaApiException 
	 */
	public static ZhimaCustomerCertificationInitializeResponse certificationInit(Map<String, String> params) throws ZhimaApiException {
		
		String bizCode = params.get("bizCode");
		ZhimaCustomerCertificationInitializeRequest req = new ZhimaCustomerCertificationInitializeRequest();
		req.setTransactionId(params.get("orderId"));// 商户流水id，每次调用确保唯一
		req.setProductCode(PRODUCT_CODE);
		req.setBizCode(bizCode);//FACE,E_SIGN
		// 个人电子签名场景入参
		Map<String, Object> identityParamMap = new HashMap<String, Object>();
		identityParamMap.put("identity_type", SignBizCodeEnum.getIdentityTypeByName(bizCode));//身份证E_SIGN_INFO,CERT_INFO
		identityParamMap.put("cert_type", "IDENTITY_CARD");
		identityParamMap.put("cert_name", params.get("certName"));
		identityParamMap.put("cert_no", params.get("certNo"));
		if(SignBizCodeEnum.E_SIGN.name().equals(bizCode)) {
			identityParamMap.put("contract_no", params.get("contractNo"));
			identityParamMap.put("sign_pos_keyword", params.get("signPosKeyword"));
			identityParamMap.put("sign_pos_x", "1");
			identityParamMap.put("sign_pos_y", "1");
		}
		req.setIdentityParam(JSON.toJSONString(identityParamMap));
		DefaultZhimaClient client = new DefaultZhimaClient(params.get("gatewayUrl"), params.get("appId"), 
				params.get("privateKey"), params.get("zimaPublicKey"));
		return client.execute(req);
	}
	
	/**
	 * 开始认证,访问返回的url唤起支付宝
	 * @param params
	 * @return
	 * String
	 * @throws ZhimaApiException 
	 */
	public static String certificationCertify(Map<String, String> params) throws ZhimaApiException {
		ZhimaCustomerCertificationCertifyRequest req = new ZhimaCustomerCertificationCertifyRequest();
		req.setBizNo(params.get("bizNo"));
		req.setReturnUrl(params.get("returnUrl"));// 回调地址
		DefaultZhimaClient client = new DefaultZhimaClient(params.get("gatewayUrl"), params.get("appId"), 
				params.get("privateKey"), params.get("zimaPublicKey"));
		return client.generatePageRedirectInvokeUrl(req);
	}
	
	/**
	 * 芝麻认证查询
	 * @param params
	 * @return
	 * ZhimaCustomerCertificationQueryResponse
	 * @throws ZhimaApiException 
	 */
	public static ZhimaCustomerCertificationQueryResponse certificationQuery(Map<String, String> params) throws ZhimaApiException {
		
		ZhimaCustomerCertificationQueryRequest req = new ZhimaCustomerCertificationQueryRequest();
		req.setBizNo(params.get("bizNo"));
		DefaultZhimaClient client = new DefaultZhimaClient(params.get("gatewayUrl"), params.get("appId"), params.get("charset"), 
				params.get("privateKey"), params.get("zimaPublicKey"),
				EncryptionModeEnum.AES, SignTypeEnum.SHA1WITHRSA, "/evQMRE/s5Iis7PG3bl4RQ==");
		return client.execute(req);
	}
	
	/**
	 * 芝麻认证回调结果解析，返回认证结果
	 * @param map
	 * @return
	 * @throws UnsupportedEncodingException
	 * String
	 * @throws ZhimaApiException 
	 */
	// 从回调地址参数解密验签得到结果(passed=true&biz_no=XXXXX)
	public static String customerCertificationresult(Map<String, String> map) throws UnsupportedEncodingException, ZhimaApiException {
		DefaultZhimaClient client = new DefaultZhimaClient(map.get("gatewayUrl"), map.get("appId"), 
				map.get("privateKey"), map.get("zimaPublicKey"));
		String params = map.get("params");
		String sign = map.get("sign");
		// 判断串中是否有%，有则需要decode
		if (params.indexOf("%") != -1) {
			params = URLDecoder.decode(params, map.get("charset"));
		}
		if (sign.indexOf("%") != -1) {
			sign = URLDecoder.decode(sign, map.get("charset"));
		}
		// 串中有空格则需要替换成+
		params = params.replaceAll(" ", "+");
		sign = sign.replaceAll(" ", "+");
		return client.decryptAndVerifySign(params, sign);
	}
}
